import React, { useState, useEffect } from 'react';
import { Card, List, Tag, Button, Typography, Empty, Spin, Alert } from 'antd';
import { Link, useParams } from 'react-router-dom';
import {  CalendarOutlined, TagOutlined } from '@ant-design/icons';
import dataService from '../../services/dataService';
import type { Bookmark } from '../../services/dataService';

const { Title, Paragraph } = Typography;
const { Meta } = Card;

const BookmarkPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }).format(date);
  };

  // 如果提供了ID，则显示单个收藏详情
  if (id) {
    const bookmark = dataService.getBookmarkById(id);
    
    if (!bookmark) {
      return (
        <div className="page-container">
          <div className="content-section">
            <div className="empty-container">
              <div className="empty-icon">🔖</div>
              <div className="empty-title">未找到该网页收藏</div>
              <div className="empty-description">
                您访问的网页收藏可能已被删除或不存在
              </div>
              <Button type="primary" size="large">
                <Link to="/bookmark">返回收藏列表</Link>
              </Button>
            </div>
          </div>
        </div>
      );
    }
    
    return (
      <div className="page-container">
        <div className="content-section">
          <div className="card-container">
            <div className="card-header">
              <Title level={2} style={{ margin: 0 }}>
                {bookmark.title}
              </Title>
            </div>
            <div className="card-body">
              <div className="mb-lg">
                <Paragraph>
                  <strong>网站地址：</strong>
                  <a 
                    href={bookmark.url} 
                    target="_blank" 
                    rel="noopener noreferrer"
                    className="d-flex align-center"
                    style={{ marginTop: '8px' }}
                  >
                    <CalendarOutlined style={{ marginRight: '4px' }} />
                    {bookmark.url}
                  </a>
                </Paragraph>
              </div>
              
              <div className="mb-lg">
                <Paragraph>
                  <strong>描述：</strong>
                </Paragraph>
                <Paragraph style={{ marginTop: '8px', color: '#666' }}>
                  {bookmark.description}
                </Paragraph>
              </div>
              
              <div className="mb-lg">
                <div className="d-flex align-center mb-sm">
                  <TagOutlined style={{ marginRight: '8px' }} />
                  <strong>标签：</strong>
                </div>
                <div className="tag-container">
                  {bookmark.tags.map(tag => (
                    <Tag key={tag} color="blue" className="tag-item">
                      {tag}
                    </Tag>
                  ))}
                </div>
              </div>
              
              <div className="mb-lg">
                <div className="d-flex align-center">
                  <CalendarOutlined style={{ marginRight: '8px' }} />
                  <strong>收藏时间：</strong>
                  <span style={{ marginLeft: '8px' }}>{formatDate(bookmark.createdAt)}</span>
                </div>
              </div>
            </div>
            <div className="card-footer">
              <div className="d-flex justify-between">
                <Button type="primary" size="large">
                  <Link to="/bookmark">返回列表</Link>
                </Button>
                <Button 
                  type="primary" 
                  size="large"
                  icon={<CalendarOutlined />}
                  href={bookmark.url}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  访问网站
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
  
  // 显示收藏列表
  const bookmarks = dataService.getBookmarks();
  
  if (loading) {
    return (
      <div className="page-container">
        <div className="loading-container">
          <Spin size="large" />
          <div className="loading-text">加载中...</div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="page-container">
        <Alert
          message="加载失败"
          description={error}
          type="error"
          showIcon
          action={
            <Button size="small" onClick={() => window.location.reload()}>
              重试
            </Button>
          }
        />
      </div>
    );
  }
  
  return (
    <div className="page-container">
      <div className="content-section">
        <div className="d-flex justify-between align-center mb-lg">
          <Title level={2} style={{ margin: 0 }}>网页收藏</Title>
          <div className="d-flex align-center">
            <span className="text-secondary">共 {bookmarks.length} 个收藏</span>
          </div>
        </div>
        
        {bookmarks.length > 0 ? (
          <div className="grid-container">
            {bookmarks.map((bookmark: Bookmark) => (
              <div key={bookmark.id} className="grid-item">
                <div className="card-container">
                  <div className="card-header">
                    <div 
                      className="bookmark-cover"
                      style={{ 
                        height: 120, 
                        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                        display: 'flex', 
                        alignItems: 'center', 
                        justifyContent: 'center',
                        borderRadius: '8px 8px 0 0',
                        margin: '-24px -24px 16px -24px'
                      }}
                    >
                      <div className="text-center">
                        <div style={{ fontSize: '32px', marginBottom: '8px' }}>🔖</div>
                        <Typography.Text style={{ color: 'white', fontWeight: 500 }}>
                          {bookmark.tags[0] || 'Bookmark'}
                        </Typography.Text>
                      </div>
                    </div>
                  </div>
                  
                  <div className="card-body">
                    <Title level={4} style={{ marginBottom: '12px' }}>
                      <a 
                        href={bookmark.url} 
                        target="_blank" 
                        rel="noopener noreferrer"
                        style={{ color: 'inherit' }}
                      >
                        {bookmark.title}
                      </a>
                    </Title>
                    
                    <Paragraph 
                      ellipsis={{ rows: 2 }} 
                      style={{ 
                        color: '#666', 
                        marginBottom: '16px',
                        minHeight: '44px'
                      }}
                    >
                      {bookmark.description}
                    </Paragraph>
                    
                    <div className="tag-container">
                      {bookmark.tags.slice(0, 3).map((tag: string) => (
                        <Tag key={tag} color="blue" className="tag-item">
                          {tag}
                        </Tag>
                      ))}
                      {bookmark.tags.length > 3 && (
                        <Tag color="default" className="tag-item">
                          +{bookmark.tags.length - 3}
                        </Tag>
                      )}
                    </div>
                    
                    <div className="d-flex align-center justify-between mt-md">
                      <div className="d-flex align-center text-secondary">
                        <CalendarOutlined style={{ marginRight: '4px' }} />
                        <span style={{ fontSize: '12px' }}>
                          {formatDate(bookmark.createdAt)}
                        </span>
                      </div>
                      <Button 
                        type="link" 
                        size="small"
                        icon={<CalendarOutlined />}
                        href={bookmark.url}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        访问
                      </Button>
                    </div>
                  </div>
                  
                  <div className="card-footer">
                    <Button type="primary" block>
                      <Link to={`/bookmark/${bookmark.id}`}>查看详情</Link>
                    </Button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="empty-container">
            <div className="empty-icon">🔖</div>
            <div className="empty-title">暂无网页收藏</div>
            <div className="empty-description">
              开始收藏您喜欢的网页，构建您的个人知识库
            </div>
            <Button type="primary" size="large">
              添加收藏
            </Button>
          </div>
        )}
      </div>
    </div>
  );
};

export default BookmarkPage;
